
package stratego.java.ssm;

import stratego.java.ssm.piece.Piece;

/**
 * <code>public final class PieceComparator</code>
 * <p>
 * This class provides a static method to compare two arbitrary pieces. I made it to fit other
 * methods for comparing pieces, but they don't seem to exist in our context.
 * </p>
 * 
 * @author Mark Aligbe
 * 
 */
public final class PieceComparator
{
	// It's a utility class, so it needs not be instantiated.
	private PieceComparator() throws AssertionError
	{
		throw new AssertionError();
	}
	
	/**
	 * <code>public static Piece comparePiece(Piece p1, Piece p2)</code>
	 * <p>
	 * Compares two pieces, and returns the one that "survives." In the case of a bomb, the callee
	 * should take appropriate action to for handling bombs.
	 * </p>
	 * 
	 * @param p1
	 *            - The first Piece to compare.
	 * @param p2
	 *            - The second Piece to compare.
	 * @return A Piece, p1 or p2, depending on which ever piece defeats the other piece. A return of
	 *         null indicates that the pieces eliminate each other.
	 */
	public static Piece comparePiece(Piece p1, Piece p2)
	{
		// First compare for "normal" pieces
		if (p1.getRank() > 0 && p2.getRank() > 0)
		{
			// Check for double eliminations
			if (p1.getRank() == p2.getRank())
				return null;
			// Check for spies
			if (p1.isSpy() && p2.getRank() == 10)
				return p1;
			else if (p2.isSpy() && p1.getRank() == 10)
				return p2;
			// Do a regular rank comparison
			if (p1.getRank() > p2.getRank())
				return p1;
			else
				return p2;
		}
		// p1 is a bomb and p2 is a regular piece
		if (p1.isBomb() && !p2.isMiner())
			return p1;
		// p1 is a bomb and p2 is a miner
		else if (p1.isBomb())
			return p2;
		// p2 is a bomb and p1 is a regular piece
		if (p2.isBomb() && !p1.isMiner())
			return p2;
		// p2 is a bomb and p1 is a miner
		else if (p2.isBomb())
			return p1;
		// If one of the pieces is a flag, then return the non-flag piece. The callee should handle
		// the winning
		if (p1.isFlag())
			return p2;
		if (p2.isFlag())
			return p1;
		// A non-deterministic case
		return null;
	}
}
